package com.whu.MenuHub.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.whu.MenuHub.domain.Order;
import com.whu.MenuHub.domain.OrderDTO;
import org.apache.ibatis.annotations.*;

@Mapper
public interface OrderDao extends BaseMapper<Order> {

    @Insert("INSERT INTO orders (userID,,addressID,orderTime,orderRectime,orderFinishTime,price," +
            "comment,commentTime,orderScore,photo,environmentScore,serviceScore,tasteScore) " +
            "VALUES (#{userID},#{addressID},#{orderTime},#{orderRectime},#{orderFinishTime},#{price}" +
            "#{comment},#{commentTime},#{orderScore},#{photo},#{environmentScore},#{serviceScore},#{tasteScore})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id",
            keyColumn = "id", resultType = Integer.class, before = false)
    void insertOrder(Order order);



    @Select("SELECT * FROM orders WHERE id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "foodJudgementList", column = "id",
                    many = @Many(select = "com.whu.MenuHub.dao.FoodCommentDao.findfoodjudgeByOrderID")),
            @Result(property = "user", column = "userID",
                    one = @One(select = "com.whu.MenuHub.dao.UserDao.selectById")),
            @Result(property = "address", column = "addressID",
                    one = @One(select = "com.whu.MenuHub.dao.ReceivingAddressDao.selectById"))
    })
    OrderDTO getOrderDetailByOderID(Integer id);


    @Select("SELECT * FROM orders ${ew.customSqlSegment}")
    IPage<Order> findOrders(IPage<Order> page,
                            @Param(Constants.WRAPPER) QueryWrapper<Order> wrapper);

    @Select("SELECT count(*) FROM orders where orders.userID=#{userID}")
    Integer getOrderNumByUserID(Integer userID);

    @Select("SELECT count(*) FROM orders where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= orders.orderTime" +
            " and orders.userID=#{userID}")
    Integer getRecentOrderNumByUserID(Integer userID);

    //根据时间查询订单数量
    @Select("SELECT COUNT(*) FROM orders WHERE TO_DAYS(NOW()) - TO_DAYS(orderTime) <= #{dayNum}")
    Integer getOrderNumByTime(int dayNum);

    //根据时间查询订单总额
    @Select("SELECT Sum(price) FROM orders where TO_DAYS(NOW()) - TO_DAYS(orderTime) <= #{dayNum}")
    Float getPriceByTime(int dayNum);
}
